import React, { useState, useEffect } from 'react'
import { Input, Table, Button, Avatar, DatePicker, Select, Card, Space, Typography } from 'antd'
import { request } from '../../utils/request'

type User = {
  id: string
  name: string
  email: string
  role: string | null
  avatar?: string | null
  lastLogin?: string | null
  loginCount?: number | null
  tokensBalance?: string | null
  tokensCompensated?: string | null
  tokensPromotional?: string | null
  tokensPurchased?: string | null
  membershipTier?: number | null
  membershipExpiresAt?: string | null
  gender?: string | null
  createdAt?: string | null
  ip?: string | null
}

const initialData: User[] = []

const Users: React.FC = () => {
  const [data, setData] = useState<User[]>(initialData)
  const [total, setTotal] = useState<number>(0)
  const [filtered, setFiltered] = useState<User[]>(initialData)
  const [query, setQuery] = useState<string>('')
  const [uuidFilter, setUuidFilter] = useState<string>('')
  const [displayNameFilter, setDisplayNameFilter] = useState<string>('')
  const [phoneFilter, setPhoneFilter] = useState<string>('')
  const [genderFilter, setGenderFilter] = useState<string | null>(null)
  const [membershipFilter, setMembershipFilter] = useState<number | null>(null)
  const [lastLoginRange, setLastLoginRange] = useState<any | null>(null)
  const [createdAtRange, setCreatedAtRange] = useState<any | null>(null)
  const [ipFilter, setIpFilter] = useState<string>('')
  // 新增/编辑功能已移除，组件仅提供查询与展示
  const [page, setPage] = useState<number>(1)
  const [pageSize, setPageSize] = useState<number>(20)
  const [loading, setLoading] = useState<boolean>(false)

  // 不在输入变化时自动触发请求或本地过滤，检索由“查询”按钮触发

  const nowrapCell = { style: { whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' } }

  const columns = [
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      width: 64,
      render: (src: string) => src ? <Avatar src={src} /> : <Avatar />,
      onHeaderCell: () => nowrapCell,
      onCell: () => nowrapCell,
    },
    { title: 'ID', dataIndex: 'id', key: 'id', width: 120, onHeaderCell: () => nowrapCell, onCell: () => nowrapCell },
    { title: '姓名', dataIndex: 'name', key: 'name', onHeaderCell: () => nowrapCell, onCell: () => nowrapCell },
    { title: '邮箱', dataIndex: 'email', key: 'email', width: 200, onHeaderCell: () => nowrapCell, onCell: () => nowrapCell },
    { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt', width: 180, render: (d: string | null) => formatDate(d), onHeaderCell: () => nowrapCell, onCell: () => nowrapCell },
    { title: 'IP', dataIndex: 'ip', key: 'ip', width: 140, onHeaderCell: () => nowrapCell, onCell: () => nowrapCell },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      width: 100,
      render: (g: string | null) => {
        if (g === null || g === undefined) return '未知'
        if (g === 'male') return '男'
        if (g === 'female') return '女'
        return '其他'
      },
      onHeaderCell: () => nowrapCell,
      onCell: () => nowrapCell,
    },
    { title: '最后登录', dataIndex: 'lastLogin', key: 'lastLogin', width: 180, render: (d: string | null) => formatDate(d), onHeaderCell: () => nowrapCell, onCell: () => nowrapCell },
    { title: '登录次数', dataIndex: 'loginCount', key: 'loginCount', width: 100, onHeaderCell: () => nowrapCell, onCell: () => nowrapCell },
    { title: '补偿余额', dataIndex: 'tokensCompensated', key: 'tokensCompensated', width: 120, render: (t: string | null) => formatToken(t), onHeaderCell: () => nowrapCell, onCell: () => nowrapCell },
    { title: '赠送余额', dataIndex: 'tokensPromotional', key: 'tokensPromotional', width: 120, render: (t: string | null) => formatToken(t), onHeaderCell: () => nowrapCell, onCell: () => nowrapCell },
    { title: '购买余额', dataIndex: 'tokensPurchased', key: 'tokensPurchased', width: 120, render: (t: string | null) => formatToken(t), onHeaderCell: () => nowrapCell, onCell: () => nowrapCell },
    { title: '余额总数', dataIndex: 'tokensBalance', key: 'tokensBalance', width: 120, render: (t: string | null) => formatToken(t), onHeaderCell: () => nowrapCell, onCell: () => nowrapCell },
    { title: '会员等级', dataIndex: 'membershipTier', key: 'membershipTier', width: 120, render: (m: number | null) => formatMembership(m), onHeaderCell: () => nowrapCell, onCell: () => nowrapCell },
    { title: '会员到期', dataIndex: 'membershipExpiresAt', key: 'membershipExpiresAt', width: 180, render: (d: string | null) => formatDate(d), onHeaderCell: () => nowrapCell, onCell: () => nowrapCell },
  ]

  // 新增用户功能已移除

  // 定义统一的请求函数，由用户点击“查询”或分页操作触发
  const fetchVisitors = async (p: number = page, ps: number = pageSize) => {
    try {
      setLoading(true)
      const body: any = { page: p, pageSize: ps }
      if (uuidFilter) body.uuid = uuidFilter
      if (query) body.email = query
      if (displayNameFilter) body.displayName = displayNameFilter
      if (phoneFilter) body.phone = phoneFilter
      if (ipFilter) body.ip = ipFilter
      if (genderFilter) body.gender = genderFilter
      if (membershipFilter !== null) body.membership_tier = membershipFilter
      if (lastLoginRange && lastLoginRange[0] && lastLoginRange[1]) {
        body.last_login_start = lastLoginRange[0].toISOString()
        body.last_login_end = lastLoginRange[1].toISOString()
      }
      if (createdAtRange && createdAtRange[0] && createdAtRange[1]) {
        body.created_at_start = createdAtRange[0].toISOString()
        body.created_at_end = createdAtRange[1].toISOString()
      }

      const res = await request.post('/api/admin/visitors', body)
      const resData = res?.data?.data ?? {}
      const visitors = resData?.visitors ?? []
      const mapped: User[] = visitors.map((v: any) => ({
        id: v.uuid,
        name: v.displayName || v.email,
        email: v.email,
        role: v.membership_tier ?? null,
        avatar: v.avatar ?? null,
        lastLogin: v.last_login ?? null,
        loginCount: v.login_count ?? null,
        tokensBalance: v.tokens_balance ?? null,
        tokensCompensated: v.tokens_compensated ?? null,
        tokensPromotional: v.tokens_promotional ?? null,
        tokensPurchased: v.tokens_purchased ?? null,
        membershipTier: v.membership_tier ?? null,
        membershipExpiresAt: v.membership_expires_at ?? null,
        gender: v.gender ?? null,
        createdAt: v.created_at ?? null,
        ip: v.ip ?? v.IP ?? v.Ip ?? null,
      }))
      setData(mapped)
      setFiltered(mapped)
      setTotal(resData.total ?? 0)
      setLoading(false)
    } catch (err) {
      // 请求错误可在此处理
      console.error(err)
      setLoading(false)
    }
  }

  // 首次挂载时请求一次（可保留），分页变化时也触发请求
  useEffect(() => {
    fetchVisitors(page, pageSize)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // 统计数据相关状态：今日、近7日、按日范围
  const [statsLoading, setStatsLoading] = useState<boolean>(false)
  const [statsData, setStatsData] = useState<any>({ today: 0, last7days: 0, range: { total: 0, by_day: [] } })
  const [statsPickerValue, setStatsPickerValue] = useState<any | null>(null)

  function formatDateYYYYMMDD(d: Date) {
    const Y = d.getFullYear()
    const M = `${d.getMonth() + 1}`.padStart(2, '0')
    const D = `${d.getDate()}`.padStart(2, '0')
    return `${Y}-${M}-${D}`
  }

  const fetchStats = async (from?: string, to?: string) => {
    try {
      setStatsLoading(true)
      let _from = from
      let _to = to
      if (!_from || !_to) {
        const today = new Date()
        _to = formatDateYYYYMMDD(today)
        const fromDate = new Date(today)
        fromDate.setDate(today.getDate() - 6) // 最近7天（包含今天）
        _from = formatDateYYYYMMDD(fromDate)
      }

      const res = await request.post('/api/admin/visitors/stats', { from: _from, to: _to })
      const d = res?.data?.data ?? {}
      setStatsData({
        today: d.today ?? 0,
        last7days: d.last7days ?? 0,
        range: d.range ?? { total: 0, by_day: [] },
      })
    } catch (err) {
      console.error(err)
    } finally {
      setStatsLoading(false)
    }
  }

  // 获取统计数据（初始化）
  useEffect(() => {
    fetchStats()
  }, [])

  // 编辑保存功能已移除

  function pad(n: number) {
    return n < 10 ? `0${n}` : `${n}`
  }

  function formatDate(d: string | null | undefined) {
    if (!d) return '--'
    const date = new Date(d)
    if (Number.isNaN(date.getTime())) return '--'
    const Y = date.getFullYear()
    const M = pad(date.getMonth() + 1)
    const D = pad(date.getDate())
    const h = pad(date.getHours())
    const m = pad(date.getMinutes())
    const s = pad(date.getSeconds())
    return `${Y}-${M}-${D} ${h}:${m}:${s}`
  }

  function formatToken(t: string | null | undefined) {
    if (t === null || t === undefined) return '--'
    // 保留两位小数并去掉多余0
    const num = Number(t)
    if (Number.isNaN(num)) return t
    return num.toFixed(2)
  }

  function formatMembership(m: number | null | undefined) {
    if (m === null || m === undefined) return '普通会员'
    if (m === 1) return '一级会员'
    if (m === 2) return '二级会员'
    if (m === 3) return '三级会员'
    return '普通会员'
  }

  // 根据按日数据计算今日/近3日/近7日的数值
  function computeSummaryFromByDay(byDay: Array<any> | undefined) {
    const arr = (byDay || []).map(d => Number(d.count || 0))
    const len = arr.length
    const todayVal = len > 0 ? arr[len - 1] : statsData.today || 0
    const last3Val = arr.slice(Math.max(0, len - 3), len).reduce((s, v) => s + v, 0)
    const last7Val = arr.slice(Math.max(0, len - 7), len).reduce((s, v) => s + v, 0)
    return { todayVal, last3Val, last7Val }
  }

  return (
    <div style={{ padding: 24, background: '#f5f7fb' }}>
      {/* 统计折线图卡片 */}
      <Card style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 24 }}>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <div style={{ color: '#666' }}>时间范围：</div>
            <DatePicker.RangePicker value={statsPickerValue} onChange={vals => setStatsPickerValue(vals)} />
            <Button onClick={() => {
              if (statsPickerValue && statsPickerValue[0] && statsPickerValue[1]) {
                const from = formatDateYYYYMMDD(statsPickerValue[0].toDate())
                const to = formatDateYYYYMMDD(statsPickerValue[1].toDate())
                fetchStats(from, to)
              } else {
                fetchStats()
              }
            }}>应用</Button>
          </div>
          {(() => {
            const { todayVal, last3Val, last7Val } = computeSummaryFromByDay(statsData.range?.by_day)
            return (
              <>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <div style={{ color: '#666' }}>今日注册</div>
                  <div style={{ fontSize: 20, fontWeight: 600 }}>{statsLoading ? '—' : todayVal}</div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <div style={{ color: '#666' }}>近三日</div>
                  <div style={{ fontSize: 20, fontWeight: 600 }}>{statsLoading ? '—' : last3Val}</div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <div style={{ color: '#666' }}>近七日</div>
                  <div style={{ fontSize: 20, fontWeight: 600 }}>{statsLoading ? '—' : last7Val}</div>
                </div>
              </>
            )
          })()}

          <div style={{ flex: 1 }} />
          <div>
            <Button onClick={() => fetchStats()} loading={statsLoading}>刷新统计</Button>
          </div>
        </div>

        {/* 简单折线图（SVG） */}
        <div style={{ marginTop: 12 }}>
          {statsData.range?.by_day && statsData.range.by_day.length > 0 ? (() => {
            const byDay = statsData.range.by_day as Array<any>
            const width = 700
            const height = 120
            const padding = 20
            const values = byDay.map(d => Number(d.count || 0))
            const max = Math.max(...values, 1)
            const stepX = (width - padding * 2) / Math.max(values.length - 1, 1)
            const points = values.map((v, i) => {
              const x = padding + i * stepX
              const y = padding + (1 - v / max) * (height - padding * 2)
              return `${x},${y}`
            }).join(' ')

            return (
              <svg width={width} height={height} style={{ width: '100%', maxWidth: 800 }}>
                <polyline points={points} fill="none" stroke="#1890ff" strokeWidth={2} />
                {values.map((v, i) => {
                  const x = padding + i * stepX
                  const y = padding + (1 - v / max) * (height - padding * 2)
                  return (
                    <React.Fragment key={i}>
                      <circle cx={x} cy={y} r={3} fill="#1890ff" />
                      <text x={x} y={y - 8} fontSize={10} textAnchor="middle" fill="#222">{v}</text>
                    </React.Fragment>
                  )
                })}
                {/* x axis labels */}
                {byDay.map((d, i) => {
                  const x = padding + i * stepX
                  return <text key={i} x={x} y={height - 4} fontSize={10} textAnchor="middle">{d.date}</text>
                })}
              </svg>
            )
          })() : <div style={{ color: '#999' }}>暂无统计数据</div>}
        </div>
      </Card>
      <Card bordered={false} style={{ marginBottom: 16 }}>
        <Space direction="vertical" style={{ width: '100%' }} size={12}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Typography.Title level={4} style={{ margin: 0 }}>访客管理</Typography.Title>
            <div style={{ flex: 1 }} />
            <div style={{ color: '#999' }}>总数：{total}</div>
          </div>

          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <Input placeholder="UUID" value={uuidFilter} onChange={e => setUuidFilter(e.target.value)} style={{ width: 220 }} />
            <Input placeholder="邮箱 (email)" value={query} onChange={e => setQuery(e.target.value)} style={{ width: 220 }} />
            <Input placeholder="显示名 (displayName)" value={displayNameFilter} onChange={e => setDisplayNameFilter(e.target.value)} style={{ width: 220 }} />
            <Input placeholder="手机号 (phone)" value={phoneFilter} onChange={e => setPhoneFilter(e.target.value)} style={{ width: 220 }} />
            <Input placeholder="IP" value={ipFilter} onChange={e => setIpFilter(e.target.value)} style={{ width: 180 }} />
            <Select placeholder="性别" value={genderFilter ?? undefined} onChange={val => setGenderFilter(val ?? null)} style={{ width: 120 }} allowClear>
              <Select.Option value="male">男</Select.Option>
              <Select.Option value="female">女</Select.Option>
              <Select.Option value="other">其他</Select.Option>
            </Select>
            <Select placeholder="会员等级" value={membershipFilter ?? undefined} onChange={val => setMembershipFilter(val ?? null)} style={{ width: 140 }} allowClear>
              <Select.Option value={1}>一级会员</Select.Option>
              <Select.Option value={2}>二级会员</Select.Option>
              <Select.Option value={3}>三级会员</Select.Option>
            </Select>
          </div>

          <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginTop: 8 }}>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <div style={{ color: '#666' }}>最后登录：</div>
              <DatePicker.RangePicker showTime onChange={vals => setLastLoginRange(vals)} />
            </div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <div style={{ color: '#666' }}>创建时间：</div>
              <DatePicker.RangePicker showTime onChange={vals => setCreatedAtRange(vals)} />
            </div>

            <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
              <Button type="primary" onClick={() => { setPage(1); fetchVisitors(1, pageSize) }}>查询</Button>
              <Button onClick={() => {
                setUuidFilter('')
                setQuery('')
                setDisplayNameFilter('')
                setPhoneFilter('')
                setGenderFilter(null)
                setMembershipFilter(null)
                setLastLoginRange(null)
                setCreatedAtRange(null)
                setPage(1)
              }}>重置</Button>
            </div>
          </div>
        </Space>
      </Card>

      <Card>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={filtered}
          loading={loading}
          // 横向自适应，纵向固定高度以便在表格内部滚动且表头固定
          scroll={{ x: 'max-content', y: 520 }}
          sticky
          pagination={{
            current: page,
            pageSize: pageSize,
            total: total,
            showTotal: (t: number) => `总数 ${t}`,
            onChange: (p: number, ps?: number) => {
              const newPageSize = ps ?? pageSize
              setPage(p)
              if (ps && ps !== pageSize) setPageSize(newPageSize)
              fetchVisitors(p, newPageSize)
            },
          }}
          bordered={false}
        />
      </Card>
    </div>
  )
}

export default Users


